package com.atlassian.jira.plugin.report;

import org.apache.lucene.document.Document;
import org.apache.lucene.search.Searchable;

import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.IssueFactory;
import com.atlassian.jira.issue.statistics.ExtendedStatsGroup;
import com.atlassian.jira.issue.statistics.util.DocumentHitCollector;

final class TwoDimensionalDocIssueHitCollector extends DocumentHitCollector
{
	private final ExtendedStatsGroup extendedStatsGroup;
	private final String luceneGroupField1;
	private final String luceneGroupField2;
	private final IssueFactory issueFactory;

	/**
	 * Main Constructor.
	 *
	 * @param extendedStatsGroup the <code>ExtendedStatsGroup</code> that allows two nested search criterions
	 * @param luceneGroupField1 the first serach/group criterion as a <code>String</code>
	 * @param luceneGroupField2 the second search/group criterion as a <code>String</code>
	 * @param searcher the Searcher
	 * @param issueFactory the <code>IssueFactory</code> for getting the issues
	 */
	public TwoDimensionalDocIssueHitCollector(ExtendedStatsGroup extendedStatsGroup,
											  String luceneGroupField1,
											  String luceneGroupField2,
											  Searchable searcher,
											  IssueFactory issueFactory)
	{
		super(searcher);
		this.extendedStatsGroup = extendedStatsGroup;
		this.luceneGroupField1 = luceneGroupField1;
		this.luceneGroupField2 = luceneGroupField2;
		this.issueFactory = issueFactory;
	}

	/**
	 * Implements method in <code>com.atlassian.jira.issue.statistics.util.DocumentHitCollector</code>
	 * Intilializes the organization of the nested group-by parameters
	 * @param document the document to get the issues from
	 */
	public void collect(Document document)
	{
		String[] values1 = document.getValues(luceneGroupField1);
		String[] values2 = document.getValues(luceneGroupField2);
		adjustMapForIssueKey(extendedStatsGroup, values1, values2, document);
	}

	/**
	 * Helper Method to collect the issue grouped by the two nested criterions
	 * @param extendedStatsGroup the <code>ExtendedStatsGroup</code> that allows two nested search criterions
	 * @param values1 a <code>String[]</code> containing the result of the first search criterion
	 * @param values2 a <code>String[]</code> containing the result of the second search criterion
	 * @param issueDocument the document to get the issues from
	 */
	private void adjustMapForIssueKey(ExtendedStatsGroup extendedStatsGroup,
									  String[] values1,
									  String[] values2,
									  Document issueDocument)
	{
		if( values1 == null || values2 == null )
			return;
		Issue issue = issueFactory.getIssue(issueDocument);
		for(int i = 0; i < values1.length; i++)
		{
			String value1 = values1[i];
			for(int j = 0; j < values2.length; j++)
			{
				String value2 = values2[j];
				extendedStatsGroup.addValue(value1, value2, issue);
			}
		}

	}
}

